<template>
  <div class="after-audio-uploaded">
    <audio-uploading v-if="uploadStatus==='uploading'" :progress="progress"></audio-uploading>
    <audio-upload-status v-if="uploadStatus!=='uploading'" :status="uploadStatus" @reupload="checkUpload"></audio-upload-status>
    <common-form :formConfig="formConfig" @input="onFormInput"></common-form>
    <div class="form-operation">
      <button class="form-btn btn-primary" :class="{'btn-disable':pushing}" @click="doSubmit(1)">发布</button>
      <button class="form-btn" @click="doSubmit(0)" v-if="!hasPublish">存草稿</button>
      <button class="form-btn" :class="{'btn-disable':pushing}"  @click="doPreview">预览</button>
      <button class="form-btn" :class="{'btn-disable':pushing}"  @click="doCancel">取消</button>
    </div>
  </div>
</template>

<script>
import AudioUploading from './audioUploading.vue';
import AudioUploadStatus from './audioUploadStatus.vue';
import CommonForm from '../../../../form/CommonForm.vue';

export default {
  name: 'AfterAudioUploaded',
  components:{
    "audio-uploading":AudioUploading,
    "audio-upload-status":AudioUploadStatus,
    "common-form":CommonForm
  },
  computed: {
    formConfig() {
      let inputs = this.formInputs;
      let formConfig = [inputs.title, inputs.cover,inputs.type];

      return formConfig.map((config) => {
        config.value = this.tempData[config.name] || config.value;
        return config;
      });
    },
    progress() {
      return this.$store.state.publishMedia.progress;
    },
    uploader() {
      return this.$store.state.publishMedia.uploader;
    },
    uploadStatus() {
      return this.$store.state.publishMedia.status;
    },
    pushing() {
      return this.$store.state.publishMedia.pushing;
    },
    tempData() {
      return this.$store.state.publishMedia.editingVideo;
    },
    formInputs() {
      return {
        title: {
          name: 'title',
          title: '音频标题',
          desc: '请输入音频标题，4-44个字符',
          require: true,
          type: 'text',
          extra: {
            placeHolder: '4-44个字符',
            limit: [4, 44, 1]
          },
          value: this.tempData.title
        },
        cover: {
          name: 'imageUrl',
          title: '音频封面',
          require: true,
          type: 'cover',
          value: this.tempData.imageUrl,
          extra: {
            fileDesc: '建议尺寸686*300,大小不超过2M',
            maxFileSize:2*1024*1024,
            width: 686,
            height: 300,
            viewWidth:154,
            viewHeight:86
          }
        },
        type: {
          name: 'previewAllowed',
          title: '是否试读',
          desc: '',
          require: true,
          type: 'radio',
          extra: {
            radio:[{
              key: 1,
              text: '允许',
              checked: true
            },{
              key: 0,
              text: '禁止',
              checked: true
            }]
          },
          value: this.tempData.previewAllowed
        }
      };
    },
    specialColumnId() {
      return this.$route.params.id;
    },
    coursePacketId() {
      return this.$route.params.issue
    },
    hasPublish() {
      let status = this.$store.state.publishMedia.editingVideo.status;
      if(!status){
        return false;
      }
      return status == 2;
    }
  },
  data() {
    return {
      formData: {},
      validate: {}
    };
  },
  methods: {
    checkUpload() {
      if (this.uploadStatus === 'uploading' && this.uploader)
        this.uploader.promise.then((res) => {
          try {
            res = window.JSON.parse(res)
          } catch (e) {}
          if (this.$store.state.publishMedia.status !== 'standby') {
            if (res.code === 200) {
              this.$store.dispatch('videoEndUpload');

              this.formData.aid = res.data.vid;
              this.formData.type = "audio";
              this.formData.mediaUrl = res.data.url;

              this.$store.dispatch('videoSetTempData', this.formData);
            }
            else {
              this.$store.dispatch('videoEndUpload', 'error');
              this.$store.dispatch('alert', res.message);
            }
          }
        }, (res) => {
          if (this.$store.state.publishMedia.status !== 'standby') {
            this.$store.dispatch('alert', res.message || '抱歉，上传失败>_<');
            this.$store.dispatch('videoEndUpload', 'error');
          }
        });
    },
    onFormInput({formData, validate, name, value}) {
      Object.assign(this.formData, formData);
      this.validate = validate;
      this.$store.dispatch('videoSetTempData', this.formData);
    },
    doSubmit(flagType) {
      if (this.uploadStatus !== 'uploaded') {
        this.$store.dispatch('alert', '请等待音频上传完毕~');
        return;
      }
      for (let i = 0; i < this.formConfig.length; i++) {
        let config = this.formConfig[i];
        let validate = this.validate[config.name];
        if (!validate.ok) {
          this.$store.dispatch('alert', `${config.title}${validate.info}`);
          return false;
        }
      }

      this.formData.coursePacketId = this.coursePacketId;
      if(this.formData.id&&!this.formData.aid){//修改
        this.formData.aid = this.formData.rid;
      }

      this.formData.flag = flagType;

      this.$store.dispatch('videoSetTempData', this.formData);
      this.$store.dispatch('audioSubmit').then(() => {
        this.$store.dispatch('alert', '提交成功！');
        this.$store.dispatch('mediaClearTempData');

        this.$router.push(`/columns/journal/${this.specialColumnId}/${this.coursePacketId}/list`);
      }, ((res) => {
        this.$store.dispatch('alert', res.message ? res.message : '抱歉，提交失败>_<');
      }));
    },
    doPreview() {
      let delay = 0;
      if (!this.previewPopup || this.previewPopup.closed) {
        let viewWidth = 900;
        let viewHeight = 800;
        let offsetLeft = (window.screen.availWidth - viewWidth)/2;
        let offsetTop = (window.screen.availHeight - 30 - viewHeight)/2;
        let url = C_OPEN + '/mob/static/column/preview.htm?type=6&project=static&id=' + this.formData.id;
        this.previewPopup = window.open(url,"",`height=${viewHeight},width=${viewWidth},top=${offsetTop},left=${offsetLeft},status=no,toolbar=no,menubar=no,location=no`);
        delay = 1500;
      }
      setTimeout(() => {
        this.previewPopup.postMessage({
          id: this.formData.id,
          title: this.formData.title,
          mediaUrl: this.formData.mediaUrl,
          description: this.formData.description,
          imageUrl: this.formData.imageUrl,
          previewAllowed: this.formData.previewAllowed
        }, C_OPEN);
        this.previewPopup.focus();
      }, delay);
    },
    doCancel() {
      if (this.$store.getters.hasTempVideoDate) {
        this.$store.dispatch('confirm', '您已输入的内容将会丢失，是否确定？').then(this.doLeave, () => {});
      }
      else {
        this.doLeave();
      }
    },
    doLeave() {
      // if (!this.isEdit) {
      try {
        this.$store.state.publishMedia.request.abort();
      }
      catch (e) {
      }
      this.$store.dispatch('mediaClearTempData');
      this.previewPopup.close();
      // }else{
      this.$emit('cancel');
      // }
    }
  },
  created() {
    this.checkUpload();
    Object.assign(this.formData, this.tempData);
  }
};
</script>

<style lang="less">
</style>
